/**
 * Created by CJB on 2016/12/13.
 */
(function ($) {

    var root = {};

    /**
     *
     * @param el 元素id
     * @param options 其他参数
     * @returns {jQuery.upload}
     */
    $.upload = function (el, options) {
        if (!(this instanceof $.upload)) {
            return new $.upload(el, options);
        }
        var self = this;

        self.$container = $(el);

        self.$container.data('upload', self);

        self.init = function () {
            self.options = $.extend({}, $.upload.defaultOptions, options);
            self.fileCount = 0;//添加的文件数量
            // 添加的文件总大小
            self.fileSize = 0;
            // 优化retina, 在retina下这个值是2
            self.ratio = window.devicePixelRatio || 1;

            // 缩略图大小
            self.thumbnailWidth = self.options.thumbnailWidth * self.ratio;
            self.thumbnailHeight = self.options.thumbnailHeight * self.ratio;

            // 所有文件的进度信息，key为file id
            self.percentages = {};
            //判断浏览器是否支持图片的base64
            self.isSupportBase64 = self.checkSupportBase64();
            //flash的版本
            self.flashVersion = self.checkFlashVersion();
            //
            self.supportTransition = self.transition();

            //检测是否支持flash
            if(!self.checkFlash())
                return ;

            self.buildQueueList();
            self.buildStatusBar();

            // 实例化
            self.uploader = WebUploader.create({
                auto:self.options.auto,
                pick: {
                    id:'#filePicker_' + self.$container.attr('id'),
                    innerHTML:self.options.pick.label
                },//{id:'',innerHTML:''},id:选择文件的按钮容器
                formData: self.options.formData,//附带的参数
                dnd: '#dndArea_' + self.$container.attr('id'),
                paste: '#' +　self.$container.attr('id'),
                swf: getPath() + 'statics/js/plug/webuploader/Uploader.swf',
                chunked: false,
                compress:false,
                server: getPath() + 'app/file/upload',
                // runtimeOrder: 'flash',
                accept: self.options.accept,

                // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
                disableGlobalDnd: true,
                fileNumLimit: 200,
                fileSizeLimit: 200 * 1024 * 1024,    // 200 M
                fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
            });
            // 添加“添加文件”的按钮，
            if(self.options.fileNumLimit > 1)
                self.uploader.addButton({
                    id: '#fileCoutinuePicker_' + self.$container.attr('id'),
                    label: '继续添加'
                });

            self.$upload.addClass( 'state-' + self.options.state );
            self.bindEvents();
            self.updateTotalProgress();

            //获取已经上传的文件
            self.remoteExistsFiles(self.options.existsFiles);
            //判断是否为只预览
            if(self.options.isPreview)
                $('#filePicker_' + self.$container.attr('id')).parent().addClass("element-invisible");
        };

        self.buildQueueList = function(){
            // 没选择文件之前的内容。
            self.$placeHolder = $( '<div id="dndArea_'+self.$container.attr('id')+'" class="placeholder"><div id="filePicker_'+self.$container.attr('id')+'"></div></div>' );
            $('<div class="queueList"></div>').append(self.$placeHolder).appendTo(self.$container);
            // 图片容器
            self.$queue = $( '<ul class="filelist"></ul>' ).appendTo( self.$container.find( '.queueList' ) );
        };

        self.buildStatusBar = function(){
            // 状态栏，包括进度和控制按钮
            self.$statusBar = $( '<div class="statusBar" style="display:none;"></div>' ).appendTo(self.$container);
            self.$progress = $( '<div class="progress"><span class="text">0%</span><span class="percentage"></span></div>' ).hide().appendTo(self.$statusBar);
            // 文件总体选择信息。
            self.$info = $( '<div class="info"></div>' ).appendTo(self.$statusBar);
            // 上传按钮
            self.$upload = $( '<div class="uploadBtn">开始上传</div>' );
            if(self.options)
                self.$upload.css('display','none');
            if(!self.options.isPreview)
                $('<div class="btns"><div id="fileCoutinuePicker_'+self.$container.attr('id')+'"></div>').append(self.$upload).appendTo(self.$statusBar);
            /*$('<div class="statusBar" style="display:none;"><div class="progress"><span class="text">0%</span>' +
                '<span class="percentage"></span></div><div class="info"></div>' +
                '<div class="btns"><div id="fileCoutinuePicker_'+self.$container.attr('id')+'"></div><div class="uploadBtn">开始上传</div></div></div>').appendTo(self.$container);*/
        };

        // 判断浏览器是否支持图片的base64
        self.checkSupportBase64 = function(){
            var data = new Image();
            var support = true;
            data.onload = data.onerror = function() {
                if( this.width != 1 || this.height != 1 ) {
                    support = false;
                }
            };
            data.src = "";
            return support;
        };

        // 检测是否已经安装flash，检测flash的版本
        self.checkFlashVersion = function() {
            var version;

            try {
                version = navigator.plugins[ 'Shockwave Flash' ];
                version = version.description;
            } catch ( ex ) {
                try {
                    version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
                        .GetVariable('$version');
                } catch ( ex2 ) {
                    version = '0.0';
                }
            }
            version = version.match( /\d+/g );
            return parseFloat( version[ 0 ] + '.' + version[ 1 ], 10 );
        };

        self.transition = function(){
            var s = document.createElement('p').style,
                r = 'transition' in s ||
                    'WebkitTransition' in s ||
                    'MozTransition' in s ||
                    'msTransition' in s ||
                    'OTransition' in s;
            s = null;
            return r;
        };

        self.checkFlash = function(){
            if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {

                // flash 安装了但是版本过低。
                if (self.flashVersion) {
                    (function(container) {
                        window['expressinstallcallback'] = function( state ) {
                            switch(state) {
                                case 'Download.Cancelled':
                                    alert('您取消了更新！');
                                    break;

                                case 'Download.Failed':
                                    alert('安装失败');
                                    break;

                                default:
                                    alert('安装已成功，请刷新！');
                                    break;
                            }
                            delete window['expressinstallcallback'];
                        };

                        var swf = getPath() +  'statics/js/plug/webuploader/expressInstall.swf';
                        // insert flash object
                        var html = '<object type="application/' +
                            'x-shockwave-flash" data="' +  swf + '" ';

                        if (WebUploader.browser.ie) {
                            html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                        }

                        html += 'width="100%" height="100%" style="outline:0">'  +
                            '<param name="movie" value="' + swf + '" />' +
                            '<param name="wmode" value="transparent" />' +
                            '<param name="allowscriptaccess" value="always" />' +
                            '</object>';

                        container.html(html);

                    })(self.$container);

                    // 压根就没有安转。
                } else {
                    self.$container.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
                }

                return false;
            } else if (!WebUploader.Uploader.support()) {
                alert( 'Web Uploader 不支持您的浏览器！');
                return false;
            }
            return true;
        };

        self.bindEvents = function(){
            // 拖拽时不接受 js, txt 文件。
            self.uploader.on( 'dndAccept', function( items ) {
                var denied = false,
                    len = items.length,
                    i = 0,
                    // 修改js类型
                    unAllowed = 'application/javascript ';

                for ( ; i < len; i++ ) {
                    // 如果在列表里面
                    if ( ~unAllowed.indexOf( items[ i ].type ) ) {
                        denied = true;
                        break;
                    }
                }

                return !denied;
            });

            //选择框打开
            /*self.uploader.on('dialogOpen', function() {
                console.log('here');
            });*/

            //
            /*self.uploader.on('ready', function() {
                window.uploader = self.uploader;
            });*/


            self.uploader.onUploadProgress = function( file, percentage ) {
                var $li = $('#'+file.id),
                    $percent = $li.find('.progress span');

                $percent.css( 'width', percentage * 100 + '%' );
                self.percentages[ file.id ][ 1 ] = percentage;
                self.updateTotalProgress();
            };

            self.uploader.onFileQueued = function( file ) {
                self.fileCount++;
                self.fileSize += file.size;

                if ( self.fileCount === 1 ) {
                    self.$placeHolder.addClass( 'element-invisible' );
                    self.$statusBar.show();
                }

                self.addFile( file );
                self.setState( 'ready' );
                self.updateTotalProgress();
            };

            self.uploader.onFileDequeued = function( file ) {
                self.fileCount--;
                self.fileSize -= file.size;

                if ( !self.fileCount ) {
                    self.setState( 'pedding' );
                }

                self.removeFile( file );
                self.updateTotalProgress();

            };

            self.uploader.on( 'all', function( type ) {
                var stats;
                switch( type ) {
                    case 'uploadFinished':
                        self.setState( 'confirm' );
                        break;

                    case 'startUpload':
                        self.setState( 'uploading' );
                        break;

                    case 'stopUpload':
                        self.setState( 'paused' );
                        break;

                }
            });

            self.uploader.onError = function( code ) {
                if('Q_TYPE_DENIED' == code)
                    createWindow('该格式不符合要求').dialog('open');
                else
                    throw new Error('[uploader] There is a eroor: "' + code);
            };

            //当文件上传成功
            self.uploader.on( 'uploadSuccess', function( file, response ) {
                if(response.isSuccess){
                    self.percentages[file.id][2] = response.resultObject;
                }else
                    alert(response.resultObject);
                //self.percentages[file.id][2] = response;
            });

            self.$upload.on('click', function() {
                if ( $(this).hasClass( 'disabled' ) ) {
                    return false;
                }

                if ( self.options.state === 'ready' ) {
                    self.uploader.upload();
                } else if ( self.options.state === 'paused' ) {
                    self.uploader.upload();
                } else if ( self.options.state === 'uploading' ) {
                    self.uploader.stop();
                }
            });

            self.$info.on( 'click', '.retry', function() {
                self.uploader.retry();
            } );

            self.$info.on( 'click', '.ignore', function() {
                //alert( 'todo' );
            } );

        };

        self.addFile = function(file){
            var suffixIndex = file.name.lastIndexOf(".") + 1;
            var suffix = file.name.substring(suffixIndex).toLowerCase();
            var previewEnable = self.options.previewTypes.indexOf(suffix) >= 0 ? true : false;

            var $li = $( '<li id="' + file.id + '">' +
                    '<p class="title">' + file.name + '</p>' +
                    '<p class="imgWrap"></p>'+
                    '<p class="progress"><span></span></p>' +
                    '</li>' ),

                $btns = $('<div class="file-panel">' +
                    '<span class="cancel" title="删除">删除</span><span class="download" title="下载">下载</span>' +
                    (previewEnable ? ('<span class="rotateRight" title="向右旋转">向右旋转</span>' +
                    '<span class="rotateLeft" title="向左旋转">向左旋转</span>') : '') +
                    '</div>').appendTo( $li ),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find( 'p.imgWrap' ).css({
                    width:self.thumbnailWidth,
                    height:self.thumbnailHeight
                }),
                $error_info = $('<p class="error"></p>'),

                showError = function( code ) {
                    switch( code ) {
                        case 'exceed_size':
                            text = '文件大小超出';
                            break;

                        case 'interrupt':
                            text = '上传暂停';
                            break;

                        default:
                            text = '上传失败，请重试';
                            break;
                    }

                    $error_info.text( text ).appendTo( $li );
                };

            if ( file.getStatus() === 'invalid' ) {
                showError( file.statusText );
            } else {
                if(previewEnable){
                    $wrap.text( '预览中' );
                    self.uploader.makeThumb( file, function( error, src ) {
                        var img;

                        if ( error ) {
                            img = $('<img src="'+getPath() + 'statics/images/icon/' + suffix +'.png">');
                            img.attr('title',file.name);
                            img.css('width', self.thumbnailWidth).css('height', self.thumbnailHeight);
                            $wrap.empty().append( img );
                            //$wrap.text( '不能预览' );
                            return;
                        }

                        if( self.isSupportBase64 ) {
                            img = $('<img src="'+src+'">');
                            img.attr('title',file.name);
                            img.dblclick(function(){
                                self.previewFile(file);
                            });
                            $wrap.empty().append( img );
                        } else {
                        }
                    }, self.thumbnailWidth, self.thumbnailHeight );

                }else{
                    var img = $('<img src="'+getPath() + 'statics/images/icon/' + suffix +'.png">');
                    img.attr('title',file.name);
                    img.css('width', self.thumbnailWidth).css('height', self.thumbnailHeight);
                    $wrap.empty().append( img );
                    //$wrap.text( '不能预览' );
                }
                file.rotation = 0;
                self.percentages[ file.id ] = [ file.size, 0 ];
            }

            file.on('statuschange', function( cur, prev ) {
                if ( prev === 'progress' ) {//上传完成
                    $prgress.hide().width(0);
                } else if ( prev === 'queued' ) {//开始上传
                    //$li.off( 'mouseenter mouseleave' );
                    //$btns.remove();
                }

                // 成功
                if ( cur === 'error' || cur === 'invalid' ) {//上传出错或文件不合格，不能上传
                    showError( file.statusText );
                    self.percentages[ file.id ][ 1 ] = 1;
                } else if ( cur === 'interrupt' ) {//上传中断，可续传
                    showError( 'interrupt' );
                } else if ( cur === 'queued' ) {//已经进入队列，等待上传
                    $error_info.remove();
                    $prgress.css('display', 'block');
                    self.percentages[ file.id ][ 1 ] = 0;
                } else if ( cur === 'progress' ) {
                    $error_info.remove();
                    $prgress.css('display', 'block');
                } else if ( cur === 'complete' ) {
                    $prgress.hide().width(0);
                    $li.append( '<span class="success"></span>' );
                }

                $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );
            });

            $li.on( 'mouseenter', function() {
                $btns.stop().animate({height: 30});
            });

            $li.on( 'mouseleave', function() {
                $btns.stop().animate({height: 0});
            });

            $btns.on( 'click', 'span', function() {
                var index = $(this).index(),
                    deg;

                switch ( index ) {
                    case 0:
                        self.uploader.removeFile( file );
                        return;

                    case 1:
                        self.downloadFile(file);
                        break;

                    case 2:
                        file.rotation += 90;
                        break;

                    case 3:
                        file.rotation -= 90;
                        break;
                }

                self.rotation($wrap,file);
            });

            $li.appendTo( self.$queue );
        };

        //
        self.remoteExistsFiles = function(ids){
            if(ids && ids.length > 0){
                post(getPath()+ 'app/file/list/' + ids,{},function(list){
                    if(list.length > 0){
                        for(var i = 0; i < list.length; i++){
                            var file= list[i];
                            self.percentages[file.id] = [file.fileSize,1,file.id];
                            self.fileCount++;
                            self.fileSize += file.fileSize;
                            self.addExistsFile(file);
                        }
                        self.$statusBar.show();
                        self.setState( 'ready' );
                        self.setState('confirm');
                        self.updateTotalProgress();
                        var text = '共' + self.fileCount + '个（' +
                            WebUploader.formatSize( self.fileSize )  +
                            '），已上传' + self.getFileCount(true) + '个';
                        self.$info.html( text );
                    }
                });
            }
        };

        //添加已经上传的文件的view
        self.addExistsFile = function(file){
            var suffix = file.postfix.toLowerCase();
            var previewEnable = self.options.previewTypes.indexOf(suffix) >= 0 ? true : false;
            //预览等按钮
            var btnsHtml = [];
            btnsHtml.push('<div class="file-panel">');
            if(!self.options.isPreview)
                btnsHtml.push('<span class="cancel" title="删除">删除</span>');
            btnsHtml.push('<span class="download" title="下载">下载</span>');
            btnsHtml.push(previewEnable ? ('<span class="rotateRight" title="向右旋转">向右旋转</span>' + '<span class="rotateLeft" title="向左旋转">向左旋转</span>') : '');
            btnsHtml.push('</div>');

            var $li = $( '<li id="' + file.id + '">' +
                    '<p class="title">' + file.fileName + '</p>' +
                    '<p class="imgWrap"></p>'+
                    '<p class="progress"><span></span></p>' +
                    '</li>' ),

                $btns = $(btnsHtml.join('')).appendTo( $li ),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find( 'p.imgWrap').css({
                    width:self.thumbnailWidth,
                    height:self.thumbnailHeight
                }),
                $error_info = $('<p class="error"></p>');

            if(previewEnable){
                var img = $('<img src="'+ getPath() + 'app/file/download/' + file.id +'">');
                img.css('width', self.thumbnailWidth).css('height', self.thumbnailHeight);
                img.attr('title',file.fileName);
                img.dblclick(function(){
                    self.previewFile(file);
                });
                $wrap.empty().append( img );
            }else{
                var img = $('<img src="'+getPath() + 'statics/images/icon/' + suffix +'.png">');
                img.css('width', self.thumbnailWidth).css('height', self.thumbnailHeight);
                img.attr('title',file.fileName);
                $wrap.empty().append( img );
                //$wrap.empty().text('不能预览');
            }
            $li.append( '<span class="success"></span>' );
            $li.addClass( 'state-complete');

            $li.on( 'mouseenter', function() {
                $btns.stop().animate({height: 30});
            });

            $li.on( 'mouseleave', function() {
                $btns.stop().animate({height: 0});
            });

            file.rotation = 0;
            $btns.on( 'click', 'span', function() {
                var index = $(this).index();

                switch ( index ) {
                    case 0://删除
                        self.fileCount--;
                        self.fileSize -= file.fileSize;
                        if ( !self.fileCount ) {
                            self.setState( 'pedding' );
                        }
                        self.removeFile( file );
                        self.updateTotalProgress();
                        return;

                    case 1:
                        self.downloadFile(file);
                        break;

                    case 2:
                        file.rotation += 90;
                        break;

                    case 3:
                        file.rotation -= 90;
                        break;
                }

                self.rotation($wrap,file);
            });

            $li.appendTo( self.$queue );
        };

        //创建预览窗口
        self.previewFile = function(file){
            if(self.percentages[file.id][1] == 1){
                var suffixIndex = file.name.lastIndexOf(".") + 1;
                var suffix = file.name.substring(suffixIndex).toLowerCase();
                var previewEnable = self.options.previewTypes.indexOf(suffix) >= 0 ? true : false;
                if(previewEnable){
                    var img = $('<img src="'+ getPath() + 'app/file/download/' + self.percentages[file.id][2] +'">');
                    img.css('width', self.options.previewWidth);
                    img.css('height', self.options.previewHeight);
                    self.createPreviewWindow(file,img);
                }else
                    createWindow('不能预览').dialog('open');
            }else{
                var suffixIndex = file.name.lastIndexOf(".") + 1;
                var suffix = file.name.substring(suffixIndex).toLowerCase();
                if(self.options.previewTypes.indexOf(suffix.toLowerCase()) >= 0){
                    self.uploader.makeThumb( file, function( error, src ) {
                        var img;

                        if ( error ) {
                            createWindow('不能预览').dialog('open');
                            return;
                        }

                        if( self.isSupportBase64 ) {
                            img = $('<img src="'+src+'">');
                            self.createPreviewWindow(file,img);
                        }
                    }, self.options.previewWidth, self.options.previewHeight );
                }else
                    createWindow('不能预览').dialog('open');
            }
        };

        //创建预览窗口
        self.createPreviewWindow = function(file,imgElement){
            var title= file.fileName ? file.fileName : file.name,
                $btns = $('<div class="file-panel">' +
                '<span class="download" title="下载">下载</span>' +
                '<span class="rotateRight" title="向右旋转">向右旋转</span>' +
                '<span class="rotateLeft" title="向左旋转">向左旋转</span>' +
                '</div>'),
                $wrap = $('<div></div>');

            self.rotation($wrap,file);
            $btns.on( 'click', 'span', function() {
                var index = $(this).index();

                switch ( index ) {
                    case 0:
                        self.downloadFile(file);
                        break;

                    case 1:
                        file.rotation += 90;
                        break;

                    case 2:
                        file.rotation -= 90;
                        break;
                }

                self.rotation($wrap,file);
            });

            var promptWindow = $("<div style='padding: 0px'></div>").append($wrap.append(imgElement)).append($btns).appendTo("html");
            promptWindow.dialog({
                autoOpen: false,
                width: self.options.previewWidth,
                height: self.options.previewHeight + 32,
                resizable: false,
                title: title,
                modal: true,
                close: function(){
                    promptWindow.remove();
                    self.rotation($('#' + file.id + ' p.imgWrap'),file);
                }
            });
            promptWindow.dialog('open');

            promptWindow.on( 'mouseenter', function() {
                $btns.stop().animate({height: 30});
            });
            promptWindow.on( 'mouseleave', function() {
                $btns.stop().animate({height: 0});
            });
        };

        self.rotation = function($wrap,file){
            if ( self.supportTransition ) {
                var deg = 'rotate(' + file.rotation + 'deg)';
                $wrap.css({
                    '-webkit-transform': deg,
                    '-mos-transform': deg,
                    '-o-transform': deg,
                    'transform': deg
                });
            } else {
                $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');
                // use jquery animate to rotation
                // $({
                //     rotation: rotation
                // }).animate({
                //     rotation: file.rotation
                // }, {
                //     easing: 'linear',
                //     step: function( now ) {
                //         now = now * Math.PI / 180;

                //         var cos = Math.cos( now ),
                //             sin = Math.sin( now );

                //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11=" + cos + ",M12=" + (-sin) + ",M21=" + sin + ",M22=" + cos + ",SizingMethod='auto expand')");
                //     }
                // });
            }
        };

        //下载文件
        self.downloadFile = function(file){
            if(self.percentages[file.id][1] == 1){
                window.open(getPath() + 'app/file/download/' + self.percentages[file.id][2]);
            }else
                createWindow('文件还在上传，无法下载').dialog('open');
        };

        // 负责view的销毁,移除文件
        self.removeFile = function ( file ) {
            var $li = $('#'+file.id);

            delete self.percentages[ file.id ];
            self.updateTotalProgress();
            $li.off().find('.file-panel').off().end().remove();
        };

        //更新上传进度
        self.updateTotalProgress = function () {
            var loaded = 0,
                total = 0,
                spans = self.$progress.children(),
                percent;

            $.each( self.percentages, function( k, v ) {
                total += v[ 0 ];
                loaded += v[ 0 ] * v[ 1 ];
            } );

            percent = total ? loaded / total : 0;

            spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );
            spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );
            self.updateStatus();
        };

        //更新状态
        self.updateStatus = function () {
            var text = '', stats;

            if ( self.options.state === 'ready' ) {
                text = '选中' + self.fileCount + '个文件，共' +
                    WebUploader.formatSize( self.fileSize ) + '。';
            } else if ( self.options.state === 'confirm' ) {
                stats = self.uploader.getStats();
                if ( stats.uploadFailNum ) {
                    text = '已成功上传' + stats.successNum + '个文件，'+
                        stats.uploadFailNum + '个文件上传失败，<a class="retry" href="#">重新上传</a>失败文件或<a class="ignore" href="#">忽略</a>'
                }

            } else {
                stats = self.uploader.getStats();
                text = '共' + self.fileCount + '个（' +
                    WebUploader.formatSize( self.fileSize )  +
                    '），已上传' + self.getFileCount(true) + '个';

                if ( stats.uploadFailNum ) {
                    text += '，失败' + stats.uploadFailNum + '个';
                }
            }

            self.$info.html( text );
        };

        //设置上传状态
        self.setState= function ( val ) {
            var file, stats;

            if ( val === self.options.state ) {
                return;
            }

            self.$upload.removeClass( 'state-' + self.options.state );
            self.$upload.addClass( 'state-' + val );
            self.options.state = val;

            switch ( self.options.state ) {
                case 'pedding':
                    self.$placeHolder.removeClass( 'element-invisible' );
                    self.$queue.hide();
                    self.$statusBar.addClass( 'element-invisible' );
                    self.uploader.refresh();
                    break;

                case 'ready'://准备上传
                    self.$placeHolder.addClass( 'element-invisible' );
                    $('#fileCoutinuePicker_' + self.$container.attr('id')).removeClass( 'element-invisible');
                    self.$queue.show();
                    self.$statusBar.removeClass('element-invisible');
                    self.uploader.refresh();
                    break;

                case 'uploading'://正在上传
                    $('#fileCoutinuePicker_' + self.$container.attr('id')).addClass( 'element-invisible' );
                    self.$progress.show();
                    self.$upload.text( '暂停上传' );
                    break;

                case 'paused'://暂停
                    self.$progress.show();
                    self.$upload.text( '继续上传' );
                    break;

                case 'confirm'://上传完成，可能存在文件上传失败
                    self.$progress.hide();
                    $( '#fileCoutinuePicker_' + self.$container.attr('id') ).removeClass( 'element-invisible' );
                    self.$upload.text( '开始上传' );

                    stats = self.uploader.getStats();
                    if ( stats.successNum && !stats.uploadFailNum ) {
                        self.setState( 'finish' );
                        return;
                    }
                    break;
                case 'finish'://上传完成，全部上传完成
                    stats = self.uploader.getStats();
                    if ( stats.successNum ) {
                        //alert( '上传成功' );
                    } else {
                        // 没有成功的图片，重设
                        self.options.state = 'done';
                        location.reload();
                    }
                    break;
            }

            self.updateStatus();
        };

        //获取文件的数量
        self.getFileCount = function(isComplete){
            if(!isComplete)
                return self.fileCount;
            var fileCount = 0;
            for(var key in self.percentages){
                if(isComplete && self.percentages[key][1] == 1)
                    fileCount++;
                else if(!isComplete)
                    fileCount++;
            }
            return fileCount;
        };

        //获取所有文件的大小
        self.getFilesSize = function(){
            var allFileSize = 0;
            for(var key in self.percentages)
                allFileSize += self.percentages[key][0];
            return allFileSize;
        };

        //获取已经上传成功的文件id
        self.getFileIds = function(){
            var ids = [];
            for(var key in self.percentages)
                if(self.percentages[key][2])
                    ids[ids.length] = self.percentages[key][2];
            return ids;
        };

        //获取上传状态
        self.getUploadState = function(){
            if(self.fileCount != self.getFileCount(true))
                return false;
            else
                return true;
        };

        self.init();

        root[el] = self;
        return self;
    };


    $.upload.defaultOptions = {
        auto:true,
        pick: {
            label: '点击选择图片'//添加文件按钮的文本
        },
        formData: {},
        //可能有pedding, ready, uploading, confirm, done.
        state:'pedding',
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        },
        // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
        disableGlobalDnd: true,
        fileNumLimit: 200,//文件总数量最大值
        fileSizeLimit: 2000 * 1024 * 1024,    // 2000 M，文件总大小最大值
        fileSingleSizeLimit: 500 * 1024 * 1024,    // 500 M，但文件大小最大值
        thumbnailWidth:110,//缩略图预览的宽度
        thumbnailHeight:110,//缩略图预览图片的高度
        previewTypes:'gif,jpg,jpeg,bmp,png',//可预览文件的类型
        isPreview:false,//是否只预览
        existsFiles:'',//已经存在的文件id，用于编辑
        previewWidth:500,//预览窗口宽度
        previewHeight:500//预览窗口高度
    };

    $.fn.getUpload = function(el){
        return root[el];
    };

})(jQuery);